﻿using ERPWinFormWork.Material.Material.Dtos;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERPWinFormWork.Material
{
    public partial class Supplier : Form
    {
        private AddContract _parentForm;
        public Supplier(AddContract parent = null)
        {
            InitializeComponent();
            _parentForm = parent;
            _apiClient = new ApiClient(MaterialAppConfig.ApiBaseUrl);
            // 添加复选框列到第一列
            if (dgvSupplier.Columns["SelectColumn"] == null)
            {
                var checkColumn = new DataGridViewCheckBoxColumn();
                checkColumn.Name = "SelectColumn";
                checkColumn.HeaderText = "选择";
                checkColumn.Width = 60;
                checkColumn.ReadOnly = false;
                checkColumn.TrueValue = true;
                checkColumn.FalseValue = false;
                dgvSupplier.Columns.Insert(0, checkColumn);
            }

            dgvSupplier.CurrentCellDirtyStateChanged += (s, e) =>
            {
                if (dgvSupplier.IsCurrentCellDirty)
                {
                    dgvSupplier.CommitEdit(DataGridViewDataErrorContexts.Commit);
                }
            };

            dgvSupplier.CellValueChanged += dgvSupplier_CellValueChanged;

            GetData();
        }

        public class ApiResponse<T>
        {
            public int code { get; set; }
            public string message { get; set; }
            public string jwt { get; set; }
            public T pageData { get; set; }
            public T data { get; set; }
            public int totalCount { get; set; }
            public int totalPages { get; set; }
        }

        private ApiClient _apiClient;
        private int PageIndex { get; set; } = 1;
        private int PageSize { get; set; } = 2;
        private int TotalCount { get; set; } = 0;
        private int TotalPages { get; set; } = 0;
        private async void GetData(Dictionary<string, string> customParams = null)
        {
            var parameters = new Dictionary<string, string>
                {
                    { "PageIndex", PageIndex.ToString() },
                    { "PageSize", PageSize.ToString() },
                };

            // 合并自定义参数（查询条件）
            if (customParams != null)
            {
                foreach (var kv in customParams)
                {
                    parameters[kv.Key] = kv.Value;
                }
            }
            var response = await _apiClient.GetAsync<ApiResponse<List<SupplierInput>>>(
                    endpoint: "Material/GetSupplier_TableShow",
                    parameters: parameters // 传递查询参数
                );
            // 处理响应结果
            if (response != null && response.code == 200)
            {
                // 将数据绑定到 DataGridView
                dgvSupplier.DataSource = response.data;

                // 初始化复选框列的值
                foreach (DataGridViewRow row in dgvSupplier.Rows)
                {
                    if (row.Cells.Count > 0)
                    {
                        row.Cells[0].Value = false;
                    }
                }
            }
        }
        /// <summary>
        /// 点击确定选中供应商
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn确定_Click(object sender, EventArgs e)
        {
            try
            {
                string selectedName = null;
                int? supplierId = null;
                
                foreach (DataGridViewRow row in dgvSupplier.Rows)
                {
                    var cellValue = row.Cells[0].Value;
                    bool isChecked = false;
                    if (cellValue is bool)
                    {
                        isChecked = (bool)cellValue;
                    }
                    else if (cellValue != null)
                    {
                        bool.TryParse(cellValue.ToString(), out isChecked);
                    }
                    if (isChecked)
                    {
                        // 根据数据源列名提取供应商名称和ID
                        if (row.DataBoundItem != null && row.DataBoundItem is SupplierInput item)
                        {
                            selectedName = item.SupplierName;
                            supplierId = item.Id;
                        }
                        else if (dgvSupplier.Columns.Contains("SupplierName"))
                        {
                            selectedName = row.Cells["SupplierName"].Value?.ToString();
                        }
                        break;
                    }
                }

                if (!string.IsNullOrWhiteSpace(selectedName) && _parentForm != null)
                {
                    _parentForm.SetSupplierName(selectedName, supplierId);
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                    return;
                }

                MessageBox.Show("请先勾选一条供应商记录。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"选择失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void dgvSupplier_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            // 确保只允许单选：当某行被勾选时，取消其他行
            if (e.RowIndex >= 0 && e.ColumnIndex == 0)
            {
                var currentRow = dgvSupplier.Rows[e.RowIndex];
                var currentChecked = false;
                var value = currentRow.Cells[0].Value;
                if (value is bool)
                {
                    currentChecked = (bool)value;
                }
                else if (value != null)
                {
                    bool.TryParse(value.ToString(), out currentChecked);
                }

                if (currentChecked)
                {
                    foreach (DataGridViewRow row in dgvSupplier.Rows)
                    {
                        if (row.Index != e.RowIndex)
                        {
                            row.Cells[0].Value = false;
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 供应商查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn查询_Click(object sender, EventArgs e)
        {
            var queryParams = new Dictionary<string, string>();

            //物料名称
            if (!string.IsNullOrWhiteSpace(tbxsuppliername.Text))
            {
                queryParams["supplierName"] = tbxsuppliername.Text;
            }
            // 调用改造后的 GetData，传入查询条件
            GetData(queryParams);
        }
        /// <summary>
        /// 供应商重置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn重置_Click(object sender, EventArgs e)
        {
            try
            {
                // 重置领料单名称输入框
                tbxsuppliername.Text = string.Empty;
                tbxsuppliername.WaterText = "请输入供应商名称";
                tbxsuppliername.SkinTxt.Text = string.Empty;
                tbxsuppliername.SkinTxt.WaterText = "请输入供应商名称";


                
                // 显示重置成功提示
                MessageBox.Show("供应商查询条件已重置！所有输入已清空，数据已重新加载。", "重置完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"重置失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
